# -*- coding: utf-8 -*-
from models import *
from limits import *
from django.shortcuts import *
from django.db.models import Q
from django.http import *
from forms import *
import re

def browse(request):
    user_id = request.session.get('user_id', '')
    if not user_id:
        return HttpResponseRedirect('/login/')
    user_id = int(user_id)
    user = User.objects.get(id = user_id)

    blogpost_list = []
    blogposts = MicroBlogPost.objects.exclude(user = user).order_by('-post_datetime')[0:BLOG_SHOW_ITEM_LENGTH]
    for blogpost in blogposts:
        sub_result = re.sub(ur'@(\w+) ', ur'@<a href = "/nick/\1">\1</a> ', blogpost.content, flags = re.U)
        blogpost_list.append((blogpost, False, sub_result))
    
    return render_to_response('browse.html',{'blogpost_list':blogpost_list, 'session_user':user})


def show_home(request, other = False, blog_id = '-1'):

    response_dict = {}
    response_dict['request_path'] = '/home/'

    user_id = request.session.get('user_id', '')
    if not user_id:

        return HttpResponseRedirect('/login/')
        
    user_id = int(user_id)
    user = User.objects.get(id = user_id)

    response_dict['follower_count'] = len(user.user_set.all())
    response_dict['fans_count'] = len(user.fans.all())
    response_dict['blog_count'] = len(user.posts_blog.all())
    response_dict['session_user'] = user
    

    if request.method == 'GET':
           
        if other == 'forward' or other == 'reply':
            blog_id = int(blog_id)
            blog_query_set = MicroBlogPost.objects.filter(id = blog_id)
            if len(blog_query_set) == 0:
                return HttpResponseNotFound()
            blog = blog_query_set[0]
            if other == 'forward':
                textarea_content = u'转@' + blog.user.nick_name + ' ' + blog.content
            else:
                textarea_content = u'@' + blog.user.nick_name + ' '

            response_dict['textarea_content'] = textarea_content
            
    # 还没有考虑到转发微博的不同特性，因此没有记录上一跳以及最终来源
    # 如果考虑扩展性的话需要修改
    else:
        
        content = request.POST.get('content', '')
        if content == '':
             return HttpResponse(u'内容不能为空')
        blog = MicroBlogPost(user = user, content = content)
        blog.save()
        compile_pattern = re.compile(ur'@(\w+) ', re.U)
        at_nick_list = compile_pattern.findall(content)

        for at_nick_name in at_nick_list:
            at_user_query_set = User.objects.filter(nick_name = at_nick_name)
            if len(at_user_query_set) == 0:
                continue
            at_user = at_user_query_set[0]
            at_user.new_at_count = at_user.new_at_count + 1
            at_user.save()
            blog.ats.add(at_user)
        blog.save()

    blogpost_list = MicroBlogPost.objects.filter(Q(user__in = user.user_set.all()) | Q(user = user)).order_by('-post_datetime')
    blogpost_page_list = blogpost_list[0:BLOG_SHOW_ITEM_LENGTH]
    blogpost_list = []
    for blogpost in blogpost_page_list:
        sub_result = re.sub(ur'@(\w+) ', ur'@<a href = "/nick/\1">\1</a> ', blogpost.content, flags = re.U)
        if blogpost.user == user:
            blogpost_list.append((blogpost, True, sub_result))
        else:
            blogpost_list.append((blogpost, False, sub_result))
    
    response_dict['blogpost_list'] = blogpost_list
    return render_to_response('home.html', response_dict)

def show_userspace(request, id_or_nick, id_or_nick_info):

    response_dict = {}

    view_user_id = request.session.get('user_id', '')
    if not view_user_id:
        return HttpResponseRedirect('/login/')
    view_user_id = int(view_user_id)
    view_user = User.objects.get(id = view_user_id)
    response_dict['session_user'] = view_user
    
    if id_or_nick == 'id':
        show_user_id = int(id_or_nick_info)
        show_user_query_set = User.objects.filter(id = show_user_id)
        if len(show_user_query_set) == 0:
            return HttpResponseNotFound()
        show_user = show_user_query_set[0]
    else:
        show_user_nick = id_or_nick_info
        show_user_query_set = User.objects.filter(nick_name = show_user_nick)
        if len(show_user_query_set) == 0:
            return HttpResponseNotFound()
        show_user = show_user_query_set[0]
        
    response_dict['same_user'] = (show_user == view_user)
    response_dict['fans_or_not'] = (view_user in show_user.fans.all())

    response_dict['nick_name'] = show_user.nick_name
    response_dict['follower_count'] = len(show_user.user_set.all())
    response_dict['fans_count'] = len(show_user.fans.all())
    response_dict['blog_count'] = len(show_user.posts_blog.all())
    
    blogpost_list = MicroBlogPost.objects.filter(user = show_user).order_by('-post_datetime')
    blogpost_page_list = blogpost_list[0:BLOG_SHOW_ITEM_LENGTH]
    blogpost_list = []
    for blogpost in blogpost_page_list:
        sub_result = re.sub(ur'@(\w+) ', ur'@<a href = "/nick/\1">\1</a> ', blogpost.content, flags = re.U)
        blogpost_list.append((blogpost, response_dict['same_user'] , sub_result))
    
    response_dict['blogpost_list'] = blogpost_list
    return render_to_response('userspace.html', response_dict)

def delete_post(request):

    if request.method == 'GET':
        return HttpResponseForbidden()

    
    user_id = request.session.get('user_id', '')
    if not user_id:
        return HttpResponseRedirect('/login/')

    user_query_set = User.objects.filter(id = user_id)
    
    if len(user_query_set) == 0:
        return HttpResponse(u'该用户不存在')
    
    user = user_query_set[0]

    delete_blog_post_id = request.POST.get('delete_post_id', '')
    if not delete_blog_post_id:
        return HttpResponse(u'未传入要删除的微博id')
    delete_blog_post_id = int(delete_blog_post_id)
    blog_query_set = MicroBlogPost.objects.filter(id = delete_blog_post_id)
    if len(blog_query_set) == 0:
        return HttpResponse(u'未找到要删除的微博')

    blog = blog_query_set[0]

    if blog.user != user:
        return HttpResponse(u'无权删除他人的微博')
    
    blog.delete()

    return HttpResponse(u'删除成功')

def show_message(request):
    receive_messages = Message.objects.filter(user_to = request.session['user_id']).order_by('send_datetime')
    send_messages = Message.objects.filter(user_from = request.session['user_id']).order_by('send_datetime')
    return render_to_response('message.html',{'send_messages':send_messages, 'receive_messages':receive_messages})

def login(request):
    if request.method == 'POST':
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            query_set = User.objects.filter(email = login_form.cleaned_data['email'])
            user = query_set[0]
            request.session['user_id'] = query_set[0].id
            return HttpResponseRedirect('/home/')
    else:
        login_form = LoginForm()
    
    return render_to_response('login.html', {'form': login_form})

def logout(request):
    
    if request.session.get('user_id', ''):
        del request.session['user_id']
    return HttpResponseRedirect('/login/')


def search(request):
    return render_to_response('search.html')


def base_style_test(request):

    return render_to_response('base.html')

def register(request):
    if request.method == 'POST':
	register_form = RegisterForm(request.POST)
	if register_form.is_valid():
	    User.objects.create(email = register_form.cleaned_data['email'], nick_name = register_form.cleaned_data['nick_name'],
				password = register_form.cleaned_data['password']) 
	    query_set = User.objects.filter(email = register_form.cleaned_data['email'])
	    request.session['user_id'] = query_set[0].id
			
	    return HttpResponseRedirect('/home/')
    else:
	register_form = RegisterForm()
    return render_to_response('register.html', {'form': register_form})

def show_fans(request):
    user = User.objects.get(id = request.session['user_id'])
    fans = user.fans.all()
    return render_to_response('fans.html', {'fans': fans})

def show_followees(request):
    user = User.objects.get(id = request.session['user_id'])
    followees = user.user_set.all()
    return render_to_response('followees.html', {'followees': followees})

def show_microblogposts(request):
    user = User.objects.get(id = request.session['user_id'])
    blogpost_list = user.posts_blog.all()
    return render_to_response('microblogposts.html', {'blogpost_list': blogpost_list})

def follow_person(request, id_or_nick, id_or_nick_info):

    if request.method == 'GET':
        return HttpResponseForbidden()
    user_id = request.session.get('user_id', '')
    if not user_id:
        return HttpResponseRedirect('/login/')

    user_query_set = User.objects.filter(id = user_id)
    
    if len(user_query_set) == 0:
        return HttpResponseRedirect('/login/')
    
    user = user_query_set[0]

    if id_or_nick == 'id':
        followee_id = int(id_or_nick_info)
        followee_query_set = User.objects.filter(id = followee_id)
    else:
        followee_nick = id_or_nick_info
        followee_query_set = User.objects.filter(nick_name = followee_nick)
        
    if len(followee_query_set) == 0:
        return HttpResponse(u'要关注的用户不存在')
    followee = followee_query_set[0]
    followee.fans.add(user)
    followee.save()

    return HttpResponse(u'已关注')

def remove_follow(request, id_or_nick, id_or_nick_info):

    user_id = request.session.get('user_id', '')
    if not user_id:
        return HttpResponseRedirect('/login/')

    user_query_set = User.objects.filter(id = user_id)
    
    if len(user_query_set) == 0:
        return HttpResponseRedirect('/login/')
    
    user = user_query_set[0]

    if id_or_nick == 'id':
        followee_id = int(id_or_nick_info)
        followee_query_set = User.objects.filter(id = followee_id)
    else:
        followee_nick = id_or_nick_info
        followee_query_set = User.objects.filter(nick_name = followee_nick)
        
    if len(followee_query_set) == 0:
        return HttpResponse(u'要取消关注的用户不存在')
    followee = followee_query_set[0]

    relation_query_set = followee.fans.filter(id = user.id)
    if len(relation_query_set) == 0:
        return HttpResponse(u'你并没有关注过该用户，不必取消关注')
    followee.fans.remove(relation_query_set[0])

    return HttpResponseRedirect("/" + id_or_nick + "/" + id_or_nick_info + "/")


